<?php
namespace app\com\simtoon\utils;
use Yii;
use app\com\simtoon\log\LogUtils;


/**
 * 2015-11-23 add by hetao
 * 用户中心API类
 */
class UserAuthUtils {

    //正式环境
//    private $client_id = "ogldSQ";
//    private $client_secret = "759946dd-28d5-41c1-91db-d619f928e840";
//    private $grant_type = "password";
//    private $scope = "basic";
//    private $url = "http://192.168.1.106:8099";
//    private $usertype = "external";//用户类型，值为internal(经纪人)或external(网站用户)。默认为网站用户

    //测试环境
    private $client_id = "ogldSQ";
    private $client_secret = "759946dd-28d5-41c1-91db-d619f928e840";
    private $grant_type = "password";
    private $scope = "basic";
    private $url = "http://115.28.76.58:8099";
    private $usertype = "external";//用户类型，值为internal(经纪人)或external(网站用户)。默认为网站用户

    /**
     * 按 . 截取token，并返回用户信息
     * @param $token
     */
    public function explode_token($token = ''){
        if(!empty($token)){
            $token = explode(".",$token);
            $str = base64_decode($token[1]);
            return json_decode($str, true);
        }
        return array();
    }

    /**
     * 网站用户使用用户名和密码登录
     * @param $username
     * @param $password
     */
    public function userPwdLogin($username, $password){
        $data ['username'] = $username;
        $data ['password'] = $password;
        $data ['usertype'] = $this->usertype;
        $data ['grant_type'] = $this->grant_type;
        $data ['scope'] = $this->scope;
        return $this->getUserLoginToken($username, $data);//返回获得token等信息
    }

    /**
     * 网站用户使用token登录
     * @param $access_token  token字符串
     */
    public function userTokenLogin($prefix, $access_token){
        $res_str = CacheUtils::getFromCache($prefix."_user_login_token");
        if($res_str && $res_str['access_token'] === $access_token){
            return true;
        }
        return false;
    }

    /**
     * 创建网站用户
     * @param array $userData 网站用户数据
     */
    public function createExternalUser(array $userData){
        LogUtils::info("Query sql={========= createExternalUser ============}", __METHOD__);
        $token = $this->getUserMngToken();
        LogUtils::info("Query sql={========= token ".$token['access_token']." ============}", __METHOD__);
        if(isset($token['error'])){
            LogUtils::info("Query sql={========= token error ".$token['error']." ============}", __METHOD__);
            return $token;
        }
        $url = $this->url . "/api/externalUsers";
        $header [] = 'Content-type: application/json';
        $header [] = 'Authorization: Bearer ' . $token['access_token'];
        $userData = json_encode($userData);
        $result = $this->postCurl($url, false, $userData, $header);
        LogUtils::info("Query sql={========= createExternalUser返回 ".$result." ============}", __METHOD__);
        $result = json_decode($result, true);//获得创建成功后的用户信息
        return $result;
    }

    /**
     * 更新网站用户信息
     * @param array $userData 网站用户数据
     */
    public function updateExternalUser(array $userData){
        $token = $this->getUserMngToken();
        if(isset($token['error'])){
            return $token;
        }
        $url = $this->url . "/api/externalUsers";
        $header [] = 'Content-type: application/json';
        $header [] = 'Authorization: Bearer ' . $token['access_token'];
        $userData = json_encode($userData);
        $result = $this->postCurl($url, false, $userData, $header, 'PUT');
        $result = json_decode($result, true);//获得创建成功后的用户信息
        return $result;
    }


    /**
     * 获得用户登录token，使用用户名和密码
     * @param string $data
     * @return mixed
     */
    public function getUserLoginToken($prefix, $data = '') {
        $url = $this->url . "/oauth/token";
        LogUtils::info("Query sql={========= getUserLoginToken ============}", __METHOD__);
        //每次登录获取token
        $result = $this->postCurl($url, true, $data, $header=0);
        LogUtils::info("Query sql={========= getUserLoginToken  返回=".$result." ============}", __METHOD__);
        $result = json_decode($result, true);
        if(!isset($result['error'])){
            LogUtils::info("Query sql={========= getUserLoginToken 成功 ============}", __METHOD__);
            CacheUtils::setToCache($prefix."_user_login_token", $result, $result['expires_in']);
        }
        return $result;
    }

    /**
     * 获得用户管理token，使用client_credentials
     */
    public function getUserMngToken() {
        $data ['grant_type'] = "client_credentials";
        $data ['scope'] = "basic";
        $url = $this->url . "/oauth/token";
        //从缓存中获取
        $res_str = CacheUtils::getFromCache("_user_mng_token");
        if ($res_str) { //存在则直接返回
            return $res_str;
            exit();
        }
        //缓存过期，则重新获取
        $result = $this->postCurl($url, true, $data, $header=0);
        $result = json_decode($result, true);
        if(!isset($result['error'])){
            CacheUtils::addToCache("_user_mng_token", $result, $result['expires_in']);
        }
        return $result;
    }

    /**
     * CURL Post
     */
    private function postCurl($url, $token = false, $data, $header = 0, $type = 'POST') {
        $curl = curl_init();
        if($header === 0){
            $header = array();
        }
        curl_setopt($curl, CURLOPT_URL,$url);
        if($token){ //是否获取token
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($curl, CURLOPT_USERPWD, $this->client_id.":".$this->client_secret);
        }
        if (!empty($data) && is_array($data)){
            $data = http_build_query($data);
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }else{
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data); //JSON数据
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $type);
        $result = curl_exec ($curl);
        curl_close($curl);
        return $result;

    }


}

?>